package com.msx.user.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.msx.constants.IsDeleteEnum;
import com.msx.pojo.*;
import com.msx.user.mapper.*;
import com.msx.util.HttpClientUtils;
import com.msx.util.MD5Sign;
import com.msx.util.ResponseResult;
import com.msx.util.StatusCode;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * 绑卡验证
 */
@Service
@Log4j2
public class TiedcardService {

    @Value("${user.cardId}")
    private String merId;
    @Value("${user.appSercret}")
    private String appSercret;

    @Autowired
    private TiedcardMapper tiedcardMapper;

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private Smslmpl smslmpl;

    //银行卡简称
    @Autowired
    private TbBankShortMapper tbBankShortMapper;

    @Autowired
    private IdentityMapper identityMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private BlackMapper blackMapper;


    /**
     * 发送信息
     * 存入redis
     * @param tiedcard
     * @return
     */
    public ResponseResult TiedcardOut(Tiedcard tiedcard){

        String mess = (String) redisTemplate.opsForValue().get(tiedcard.getReservedMobile()+tiedcard.getUserId());

        //如果mess为空
        if (StringUtils.isBlank(mess)){
        //发送信息获取验证码
        String inde = inde(tiedcard);

        //存入redis
        Boolean aBoolean = InterRedis(inde, tiedcard);

        //判断状态
        if (aBoolean){
            //状态存入redis sms.getMobile()+sms.getUserId()
            redisTemplate.opsForValue().set(tiedcard.getReservedMobile()+tiedcard.getUserId(),"绑卡获取验证码",1,TimeUnit.MINUTES);
            //保存信息
            addsms(tiedcard,inde);

            String data = JSON.parseObject(inde).getString("data");

            return new ResponseResult(StatusCode.OK,"获取成功",data);
        }
            return new ResponseResult(StatusCode.ERROR,"绑卡验证码获取有误，请重新获取");
        }
          return new ResponseResult(StatusCode.ERROR,"您以获取验证码,请稍后获取");

    }

    //保存发送信息
    public void addsms(Tiedcard tiedcard, String in){
        Sms sms = new Sms();
        sms.setSmsType("安全认证(绑定银行卡)");
        sms.setIsDelete(String.valueOf(IsDeleteEnum.OK.getCode()));
        sms.setContent(in);
        sms.setUserId(tiedcard.getUserId());
        sms.setSendTime(new Date());
        sms.setMobile(tiedcard.getReservedMobile());
        smslmpl.SmsAdd(sms);
    }

    /**
     * 根据id查询
     * @return
     */
    public TbBankShort findById(int id){
        return tbBankShortMapper.selectByPrimaryKey(id);
    }

    /**
     * 添加信息
     * 修改状态
     * @param tiedcard
     */
    public ResponseResult indeupdate(Tiedcard tiedcard){

        //获取数据
        String code = tiedcard.getCode();
        String reservedMobile = tiedcard.getReservedMobile();
        String s =(String) redisTemplate.opsForValue().get(tiedcard.getReservedMobile()+"code");
        String bind = (String) redisTemplate.opsForValue().get(tiedcard.getReservedMobile()+"bind");
        tiedcard.setBindcardid(bind);

        //比较验证码是否正确
        if (!StringUtils.isNotEmpty(s)){
            return new ResponseResult(StatusCode.ERROR,"验证码已过期");
        }
        if (!StringUtils.isNotEmpty(bind)){
            return new ResponseResult(StatusCode.ERROR,"协议号已过期");
        }
        if (code.equals(s)){
            return update(tiedcard);
        }

        return new ResponseResult(StatusCode.ERROR,"绑卡认证失败");
    }

    /**
     * 修改权限
     * @param tiedcard
     * @return
     */
    @Transactional
    public ResponseResult update(Tiedcard tiedcard){
        try {
            //修改绑卡列表
            tiedcard.setIsDelete(String.valueOf(IsDeleteEnum.OK.getCode()));
            tiedcard.setCreateTime(new Date());
            tiedcardMapper.insertSelective(tiedcard);

            //修改用户
            User user = new User();
            user.setCardAuthentication(String.valueOf(IsDeleteEnum.ERROR.getCode()));
            user.setId(tiedcard.getUserId());
            userMapper.updateByPrimaryKeySelective(user);

            //添加银行卡列表
            AddblackList(tiedcard);
            return new ResponseResult(StatusCode.OK,"完成绑卡操作");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new ResponseResult(StatusCode.ERROR,"权限修改失败") ;
    }

    //添加银行卡
    public void AddblackList(Tiedcard tiedcard){
        Black black = new Black();
        black.setCreateTime(new Date());
        black.setUpdateTime(new Date());
        black.setCreateBy(tiedcard.getName());
        black.setUserName(tiedcard.getName());
        black.setIdentityCode(tiedcard.getIdentityCode());
        black.setMobile(tiedcard.getReservedMobile());
        black.setUpdateBy(tiedcard.getName());
        black.setIsDelete(String.valueOf(IsDeleteEnum.OK.getCode()));
        blackMapper.insertSelective(black);
    }


    /**
     * 存入redis
     * @param out
     */
    public Boolean InterRedis(String out, Tiedcard tiedcard){
        //存储哨兵
        Boolean falg = false;

        //格式转换
        JSONObject jsonObject = JSON.parseObject(out);
        JSONObject string = jsonObject.getJSONObject("data");
        log.info("绑定银行卡发送信息:"+string);

        //获取对应值
        String code = string.getString("code");
        String bindCardId = string.getString("bindCardId");

        //存入redis
        redisTemplate.opsForValue().set(tiedcard.getReservedMobile()+"code",code,3, TimeUnit.MINUTES);
        redisTemplate.opsForValue().set(tiedcard.getReservedMobile()+"bind",bindCardId,3, TimeUnit.MINUTES);

        //获取
        String t1 = (String) redisTemplate.opsForValue().get(tiedcard.getReservedMobile() + "code");
        String t2 = (String) redisTemplate.opsForValue().get(tiedcard.getReservedMobile() + "bind");
        //安全优化
        if (StringUtils.isNotEmpty(t1) && StringUtils.isNotEmpty(t2)){
            falg=true;
        }
        return falg;
    }
    /**
     * 第三方接口发送短信
     * @param tiedcard
     * @return
     */
    public String inde(Tiedcard tiedcard){
        String url="http://localhost:8080/api/common/bindCardSms";
        Map<String,String> map = new HashMap<>();
        map.put("merId",merId);
        map.put("name",tiedcard.getName());
        map.put("cardId",tiedcard.getIdentityCode());
        //银行卡
        map.put("accNo",tiedcard.getBankCode());

        //查询银行卡信息
        TbBankShort aShort = findById(tiedcard.getBankId());
        System.out.println(aShort);
        //银行名称
        map.put("bankName",aShort.getBankName());
        //银行卡简称
        map.put("bankShortName",aShort.getBankShortName());
        //预留手机号
        map.put("reserveMobile",tiedcard.getReservedMobile());
        String sign = MD5Sign.sign(map,appSercret);
        map.put("sign",sign);
        String str = HttpClientUtils.httpPost(url,map);
        return str;
    }

    /**
     * 查询
     * @param id
     * @return
     */
    public ResponseResult findByID(String id){
        Map list = new HashMap();
        Example example = new Example(Identity.class);
        example.createCriteria().andEqualTo("userId",id);
        example.createCriteria().andEqualTo("isDelete",String.valueOf(IsDeleteEnum.OK.getCode()));
        List<Identity> identities = identityMapper.selectByExample(example);
        Identity identity1 = identities.get(identities.size()-1);

        //如果不为空继续查询
        if (!StringUtils.isBlank(identity1.toString())){
            list.put("user",identity1);

            List<TbBankShort> tbBankShorts = tbBankShortMapper.selectByExample(null);
            list.put("bankshow",tbBankShorts);

            return new ResponseResult().success(list);
        }

        return new ResponseResult().error(StatusCode.ERROR,"没有此用户");
    }
    public Tiedcard findByIduserid(Integer userid){
        return  tiedcardMapper.findByIduserid(userid);
    }
}
